
_G.test1 = {}

module(...,package.seeall)

require "sys"
require"misc"   --包含一些系统级的辅助函数，例如读取电池电压、获取系统状态等。
require "testHttp"
require "testCamera" -- 加载CAMERA功能测试模块
require"pins"
pins.setup(pio.P0_12,0)
-- gpio.setup(12, 0)

-- 获取当前时间
local nowTime = misc.getClock()

-- 定义一个日期时间表
local DateTime = {
    year = 0,
    month = 0,
    day = 0,
    hour = 0,
    minute = 0,
    second = 0
}

-- 定义一个日期时间表
local wantTime = {
    year = 0,
    month = 0,
    day = 0,
    hour = 0,
    minute = 0,
    second = 0
}

-- 想要开启的时间
local wantOpenHour = 17
local wantOpenMin = 40
local wantOpenSec = 0

-- 判断是否为闰年
local function is_leap_year( year )
    return (year % 4 == 0 and year % 100 ~= 0) or (year % 400 == 0);
end

-- 获取某个月份的天数
local function days_in_month( year, month )
    print("传进来的year"..year)
    print("传进来的month"..month)
    local days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if month == 2 and is_leap_year(year) then
        return 29
    else
        if days[month] ~= nil then
            print("days[month]不是nil"..days[month])
        else
            print("days[month]是nil")
        end
        return days[month]
    end
end

-- 将日期时间转换为 Unix 时间戳（秒）
local function datetime_to_timestamp( dt )
    -- 上海时间（CST）是 UTC+8，所以我们需要减去 8 小时
    local utc_dt = {year = dt.year,
                    month = dt.month, 
                    day = dt.day, 
                    hour = dt.hour - 8, 
                    minute = dt.minute, 
                    second = dt.second}
    if utc_dt.year ~= nil then
        print("utc_dt.year不是nil"..utc_dt.year)
    else
        print("utc_dt.year是nil")
    end
    if utc_dt.month ~= nil then
        print("utc_dt.month不是nil"..utc_dt.month)
    else
        print("utc_dt.month是nil")
    end
    if utc_dt.day ~= nil then
        print("utc_dt.day不是nil"..utc_dt.day)
    else
        print("utc_dt.day是nil")
    end
    if utc_dt.hour ~= nil then
        print("utc_dt.hour不是nil"..utc_dt.hour)
    else
        print("utc_dt.hour是nil")
    end
    if utc_dt.minute ~= nil then
        print("utc_dt.minute不是nil"..utc_dt.minute)
    else
        print("utc_dt.minute是nil")
    end
    if utc_dt.second ~= nil then
        print("utc_dt.second不是nil"..utc_dt.second)
    else
        print("utc_dt.second是nil")
    end
    print("计算完北京时间", string.format("%04d/%02d/%02d,%02d:%02d:%02d", utc_dt.year, utc_dt.month, utc_dt.day, utc_dt.hour, utc_dt.minute, utc_dt.second))

    -- 减去 8 小时（考虑可能跨日的情况）
    if utc_dt.hour < 0 then
        utc_dt.hour = utc_dt.hour + 24
        utc_dt.day = utc_dt.day - 1
        if utc_dt.day < 1 then
            utc_dt.month = utc_dt.month - 1
            if utc_dt.month < 1 then
                utc_dt.month = 12
                utc_dt.year = utc_dt.year - 1
            end
            utc_dt.day = days_in_month(utc_dt.year, utc_dt.month)
        end
    end

    -- 计算年份的天数（从 1970 开始）
    local total_days = 0

    -- 1970 年之前的时间戳为负数，这里只处理 1970 年及之后
    if utc_dt.year < 1970 then 
        return 0
    end

    -- 计算整年的天数
    for y = 1970, utc_dt.year - 1 do
        total_days = total_days + (is_leap_year(y) and 366 or 365)
    end

    -- 计算当前年的天数
    for m = 1, utc_dt.month - 1 do
        print(" 月 ", m)
        if total_days ~= nil then
            print(" total_days不是空 ", total_days)
        else
            print(" total_days是空 ", total_days)
        end
        if utc_dt.year ~= nil then
            print(" utc_dt.year不是空 ", utc_dt.year)
        else
            print(" utc_dt.year是空 ", utc_dt.year)
        end
        if m ~= nil then
            print(" m不是空 ", m)
        else
            print(" m是空 ", m)
        end
        total_days = total_days + days_in_month(utc_dt.year, m)
    end

    -- 当前月的天数
    total_days = total_days + utc_dt.day - 1

    -- 转换为秒
    local seconds = total_days * 86400
    seconds = seconds + utc_dt.hour * 3600
    seconds = seconds + utc_dt.minute * 60
    seconds = seconds + utc_dt.second

    return seconds
end


-- 将时间戳转换为日期时间
local function timestamp_to_datetime(timestamp)
    timestamp = timestamp + 8 * 3600 -- 转换为 UTC 时间

    -- 计算天数
    local days = timestamp / 86400
    local seconds = timestamp % 86400

    -- 设置 UTC 时间部分
    local utc_dt = {year = 1970, month = 1, day = 1, hour = 0, minute = 0, second = 0} -- Unix 纪元起点
    utc_dt.second = seconds % 60
    seconds = math.floor(seconds / 60)
    utc_dt.minute = seconds % 60
    utc_dt.hour = math.floor(seconds / 60)

    -- 计算年份
    local year = 1970
    while true do
        local days_in_year = is_leap_year(year) and 366 or 365
        if days < days_in_year then break end
        days = days - days_in_year
        year = year + 1
    end
    utc_dt.year = year

    -- 计算月份
    local month = 1
    while month <= 12 do
        local days_in_mon = days_in_month(year, month)
        if days < days_in_mon then break end
        days = days - days_in_mon
        month = month + 1
    end
    utc_dt.month = month

    utc_dt.day = days + 1

    return utc_dt
end

-- 计算当前时间戳（简单模拟）
local function get_current_timestamp( nowTime )
    local dt = {year = nowTime.year, month = nowTime.month, day = nowTime.day, hour = nowTime.hour, minute = nowTime.min, second = nowTime.sec }
    if dt.year<2025 then
        sys.restart('程序超时软件重启，年份小于2025')
    end
    if nowTime.year ~= nil then
        print("nowTime.year不是nil"..nowTime.year)
    else
        print("nowTime.year是nil")
    end
    if nowTime.month ~= nil then
        print("nowTime.month不是nil"..nowTime.month)
    else
        print("nowTime.month是nil")
    end
    if nowTime.day ~= nil then
        print("nowTime.day不是nil"..nowTime.day)
    else
        print("nowTime.day是nil")
    end
    if nowTime.hour ~= nil then
        print("nowTime.hour不是nil"..nowTime.hour)
    else
        print("nowTime.hour是nil")
    end
    if nowTime.min ~= nil then
        print("nowTime.min不是nil"..nowTime.min)
    else
        print("nowTime.min是nil")
    end
    if nowTime.sec ~= nil then
        print("nowTime.sec不是nil"..nowTime.sec)
    else
        print("nowTime.sec是nil")
    end
    return datetime_to_timestamp(dt)
end

-- 计算时间戳的差值
local function calculate_diff(target_timestamp)
    local nowTime = misc.getClock()
    local current = get_current_timestamp( nowTime )
    return target_timestamp - current
end

-- 计算想要开启的时间
local function openTime( openHour, openMin, openSec )
    local tm = misc.getClock()
    log.info("获取的时间", string.format("%04d/%02d/%02d,%02d:%02d:%02d", tm.year, tm.month, tm.day, tm.hour, tm.min, tm.sec))
    print("获取的时间", string.format("%04d/%02d/%02d,%02d:%02d:%02d", tm.year, tm.month, tm.day, tm.hour, tm.min, tm.sec))
    -- 如果还没到想要开启的时间
    if tm.hour < openHour or 
    ( tm.hour == openHour and tm.min < openMin) or 
    (tm.hour == openHour and tm.min == openMin and tm.sec < openSec ) then
        wantTime.year = tm.year
        wantTime.month = tm.month
        wantTime.day = tm.day
        wantTime.hour = openHour
        wantTime.minute = openMin
        wantTime.second = openSec
    -- 如果过了到想要开启的时间
    else
        local monthDay = days_in_month( tm.year, tm.month )
        print( "这个月天数monthDay是" ..monthDay)
        -- 如果是月末的一天
        if (tm.day + 1) > monthDay then
            if tm.month == 12 then
                wantTime.year = tm.year + 1
                wantTime.month = 1
                wantTime.day = 1
                wantTime.hour = openHour
                wantTime.minute = openMin
                wantTime.second = openSec
            else
                wantTime.year = tm.year
                wantTime.month = tm.month + 1
                wantTime.day = 1
                wantTime.hour = openHour
                wantTime.minute = openMin
                wantTime.second = openSec
            end
        else
            wantTime.year = tm.year
            wantTime.month = tm.month
            wantTime.day = tm.day + 1
            wantTime.hour = openHour
            wantTime.minute = openMin
            wantTime.second = openSec
        end
    end
end

-- 传入想开启的时间，返回计算与现在时间的时间差  (单位：秒)
local function Dtime( wHour, wMin, wSec)
    openTime( wHour, wMin, wSec )
    print("计算函数过去了")
    local target_dt = { year = wantTime.year, 
                        month = wantTime.month, 
                        day = wantTime.day, 
                        hour = wantTime.hour, 
                        minute = wantTime.minute, 
                        second = wantTime.second}
    log.info("想要的时间", string.format("%04d/%02d/%02d,%02d:%02d:%02d", wantTime.year, wantTime.month, wantTime.day, wantTime.hour, wantTime.minute, wantTime.second))
    print("想要的时间", string.format("%04d/%02d/%02d,%02d:%02d:%02d", wantTime.year, wantTime.month, wantTime.day, wantTime.hour, wantTime.minute, wantTime.second))
    local target_timestamp = datetime_to_timestamp( target_dt ) -- 目标时间转换成时间戳
    print("目标时间转化时间戳成功")
    local nowTime = misc.getClock()
    local current_timestamp = get_current_timestamp( nowTime )  -- 当前时间转换成时间戳
    print("当前时间转化时间戳成功")
    local diff_seconds = calculate_diff( target_timestamp )     -- 计算时间差

    print("当前时间: " .. current_timestamp .. " (时间戳)")
    print("目标时间: " .. target_timestamp .. " (时间戳)")
    if diff_seconds > 0 and diff_seconds <= 86400 then
        print("距离目标时间还需: " .. diff_seconds .. " 秒")
        local diff_hours = math.floor(diff_seconds / 3600)
        print("距离目标时间还需: " .. diff_hours .. " 小时")
        local diff_hours2 = diff_seconds / 3600
        print("距离目标时间还需: %.2f 小时" , diff_hours2 )
    elseif diff_seconds < 0 then
        print("距离目标时间已过: " .. -diff_seconds .. " 秒")
        local diff_hours = math.floor(-diff_seconds / 3600)
        print("距离目标时间已过: %.2f" .. diff_hours .. " 小时")
        local diff_hours2 = -diff_seconds / 3600
        print("距离目标时间已过: " .. diff_hours2 .. " 小时")
    else
        sys.restart('程序超时软件重启,时间差大于一天,86400秒')
    end

    local dt_current = timestamp_to_datetime( current_timestamp )   -- 时间戳转换回时间
    local dt_target = timestamp_to_datetime( target_timestamp )     -- 时间戳转换回时间 

    print("\n当前日期时间: " ..
          string.format("%04d-%02d-%02d %02d:%02d:%02d",
                        dt_current.year, dt_current.month, dt_current.day,
                        dt_current.hour, dt_current.minute, dt_current.second))

    print("目标日期时间: " ..
          string.format("%04d-%02d-%02d %02d:%02d:%02d",
                        dt_target.year, dt_target.month, dt_target.day,
                        dt_target.hour, dt_target.minute, dt_target.second))
    return diff_seconds
end

-- 定义要运行的函数
local function myDailyFunction()
    -- print("Function is running at 12:00!")
    print("运行了一遍")
    -- 在这里添加你的逻辑
end

-- 计算下一次 12 点的时间间隔（单位：秒）
local function calculateNext12OClock()
    -- local now = os.time() -- 获取当前时间，返回的是秒级时间戳
    -- -- log.info(" now is ", now)
    -- local now_tm = os.date("*t", now) -- 将时间戳转换为时间表
    -- log.info(" now_tm is ", now_tm)
    local tm = misc.getClock()

    -- 计算到下一次 12 点的秒数
    local secondsTo12 = 0
    if tm.hour < sHour or ( tm.hour == sHour and tm.min < sMin) or (tm.hour == sHour and tm.min == sMin and tm.sec < sSecLO ) then
        -- 如果当前时间小于 12 点，计算到今天 12 点的秒数
        secondsTo12 = ( sHour - tm.hour ) * 3600 + (sMin - tm.min) * 60 + (sSecLO - tm.sec)
        log.info(" 小于12点 secondsTo12 is ", secondsTo12)
    else
        -- 如果当前时间大于或等于 12 点，计算到明天 12 点的秒数
        secondsTo12 = ((24 - tm.hour + 1) * 3600 + (60 - tm.min) * 60 + (60 - tm.sec) + 3600*24 - ( sMin*60 + 15 ))
        secondsTo12 = secondsTo12 + sHour * 3600
        log.info(" 过了12点 secondsTo12 is ", secondsTo12)
    end

    return secondsTo12
end

local function testTimed()
    local tm = misc.getClock()

    -- 计算到下一次 12 点的秒数
    local secondsTo12 = 0
    if tm.hour < sHour or ( tm.hour == sHour and tm.min < sMin) or (tm.hour == sHour and tm.min == sMin and tm.sec < sSec ) then
        -- 如果当前时间小于 12 点，计算到今天 12 点的秒数
        secondsTo12 = ( sHour - tm.hour ) * 3600 + (sMin - tm.min) * 60 + (sSecLO - tm.sec)
        print(" 小于%d:%d:%d",sHour,sMin,sSecLO)
        print("secondsTo12 is ", secondsTo12,"还差小时",secondsTo12/3600)
    else
        -- 如果当前时间大于或等于 12 点，计算到明天 12 点的秒数
        secondsTo12 = ((24 - tm.hour + 1) * 3600 + (60 - tm.min) * 60 + (60 - tm.sec) + 3600*24 - ( sMin*60 + 15 ))
        secondsTo12 = secondsTo12 + sHour * 3600
        print(" 大于%d:%d:%d",sHour,sMin,sSecLO)
        print("secondsTo12 is ", secondsTo12,"还差小时",secondsTo12/3600)
    end
end


-- sys.taskInit(function ()
--     log.info( " 等待线程1 " )
--     print( " 等待线程1 " )
--     sys.wait(10000)
--     test1.cameraTest()  -- 开机拍照上传一次
-- end
-- )

-- sys.taskInit(function ()
--     sys.wait(25000)
--     log.info( " 线程2开启 " )
--     print( " 线程2开启 " )
--     print( " 开始计算 " )
--     print( " 开始计算 " )
--     print( " 开始计算 " )

--     sys.timerLoopStart(function ()
--         test1.cameraTest()
--     end,120000)

--     -- sys.timerStart(paizhao(), 1000)

--     sys.timerLoopStart(function ()
--         print("程序还活着")
--     end,3600000)
-- end
-- )

-- local tcount1 = 0
-- local tcount2 = 0
-- local taskNum = 0
-- local tid
-- tid = sys.timerLoopStart(function(a, b, c)
--     if taskNum == 0 then
--         print("线程1输入值是", a, b, c, tcount1) -- 1000毫秒后才会执行, 打印 task A B N
--         if tcount1 > 10 then
--             sys.timerStop(tid)
--             print("线程1停止")
--             taskNum = 1
--             print("taskNum 是" .. taskNum)
--         end
--         tcount1 = tcount1 + 1
--     end
-- end, 1000, "A", "B", "N")
-- local wid
-- wid = sys.timerLoopStart(function(a, b, c)
--     if taskNum == 1 then
--         print("线程2输入值是", a, b, c, tcount2) -- 1000毫秒后才会执行, 打印 task A B N
--         if tcount2 > 10 then
--             sys.timerStop(wid)
--             print("线程2停止")
--             taskNum = 0
--             print("taskNum 是" .. taskNum)
--         end
--         tcount2 = tcount2 + 1
--     end
-- end, 1000, "C", "D", "M")



sys.taskInit(function ()
    log.info( " 等待线程1 " )
    print( " 等待线程1 " )
    sys.wait(10000)
    pins.setup(pio.P0_12,1)
    test1.cameraTest()  -- 开机拍照上传一次
end
)

sys.taskInit(function ()
    sys.wait(25000)
    log.info( " 线程2开启 " )
    print( " 线程2开启 " )
    print( " 开始计算 " )
    print( " 开始计算 " )
    print( " 开始计算 " )

    sys.timerLoopStart(function ()
        pins.setup(pio.P0_12,1)
        test1.cameraTest()
    end,15*1000)

    -- sys.timerLoopStart(function ()
    --     print("程序还活着")
    -- end,3600000)
end
)




